package kr.ac.mju.mdc.mjuapp.web;

import kr.ac.mju.mdc.mjuapp.R;
import kr.ac.mju.mdc.mjuapp.login.LoginActivity;
import kr.ac.mju.mdc.mjuapp.network.NetworkManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.webkit.CookieSyncManager;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author davidkim
 * 
 */
public class WebViewActivity extends Activity {
	private String rootUrl = null;
	private String oldRootUrl = null;

	private static final int PROGRESS_DIALOG = 11;
	private static final int LOGIN_DIALOG = 12;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.webview_layout);
		// init
		init();
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		switch (id) {
		case PROGRESS_DIALOG:
			Dialog progressDialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar);
			progressDialog.setContentView(R.layout.loading_progress);
			progressDialog.setCancelable(true);
			return progressDialog;
		case LOGIN_DIALOG:
			return new AlertDialog.Builder(this).setTitle("명지대학교").setMessage(getString(R.string.msg_login_alert))
					.setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.cancel();
							// Login Activity
							Intent loginIntent = new Intent(WebViewActivity.this, LoginActivity.class);
							startActivity(loginIntent);
							// WebView white page back
							((WebView) findViewById(R.id.webview)).goBack();
						}
					}).setCancelable(true).create();
		default:
			return null;
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// cookie
		CookieSyncManager.createInstance(getApplicationContext());
		CookieSyncManager.getInstance().startSync();
		// get rootUrl
		rootUrl = getIntent().getExtras().getString("rooturl");
		if (rootUrl != null) {
			// check network state
			if (NetworkManager.checkNetwork(this)) {
				// webView set
				WebView webView = (WebView) findViewById(R.id.webview);
				if (oldRootUrl == null) {
					webView.loadUrl(rootUrl);
					oldRootUrl = rootUrl;
				} else if (!oldRootUrl.equals(rootUrl)) {
					webView.loadUrl(rootUrl);
					oldRootUrl = rootUrl;
				}
			}
			// set titlebar
			setTitlebar();
		}
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		// cookie
		CookieSyncManager.getInstance().stopSync();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		// TODO Auto-generated method stub
		super.onNewIntent(intent);
		setIntent(intent);
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		WebView webView = (WebView) findViewById(R.id.webview);

		if (webView.getUrl() != null) {
			if (webView.getUrl().equals(rootUrl) || !webView.canGoBack())
				super.onBackPressed();
			else
				webView.goBack();
		} else
			finish();
	}

	/**
	 * 
	 */
	private void init() {
		// webView setting
		WebView webView = (WebView) findViewById(R.id.webview);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.setWebViewClient(new WebViewClient() {
			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				// TODO Auto-generated method stub
				super.onPageStarted(view, url, favicon);

				// 캠퍼스맵일 경우 웹브라우저 확대 축소 가능
				if (url.equals("http://www.mju.ac.kr/mbs/mjumob2/images/img_map01.png")
						|| url.equals("http://www.mju.ac.kr/mbs/mjumob2/images/img_map02.png"))
					view.getSettings().setBuiltInZoomControls(true);
				else
					view.getSettings().setBuiltInZoomControls(false);

				// 웹 페이지 진행 상황 프로그레스바 출력
				showDialog(PROGRESS_DIALOG);
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				// TODO Auto-generated method stub
				super.onPageFinished(view, url);
				// progressbar dismiss
				dismissDialog(PROGRESS_DIALOG);
				// cookie
				CookieSyncManager.getInstance().sync();
			}

			@Override
			public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
				// TODO Auto-generated method stub
				super.onReceivedError(view, errorCode, description, failingUrl);
				Toast.makeText(getApplicationContext(), "onReceivedError : " + errorCode + ", " + description, Toast.LENGTH_SHORT).show();
				// error 시 white page 출력
				if (errorCode == WebViewClient.ERROR_HOST_LOOKUP) {
					String blankPage = "<html><body></body></html>";
					view.loadData(blankPage, "text/html", "utf-8");
					view.clearHistory();
				}
			}
		});
		webView.setWebChromeClient(new WebChromeClient() {
			// JavaScript Popup handle
			@Override
			public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
				// TODO Auto-generated method stub
				// JavaScript 처리
				result.confirm();
				// 로그인 하지 않았을 경우 JavaScript 팝업 창 처리
				if (message.contains(getString(R.string.msg_login_alert))) {
					showDialog(LOGIN_DIALOG);
					return true;
				}
				return true;
			}
		});
	}

	/**
	 * 
	 */
	private void setTitlebar() {
		TextView titleTextView = (TextView) findViewById(R.id.webview_title_textview);
		ImageView headerIconView = (ImageView) findViewById(R.id.webview_header_icon);
		if (rootUrl.equals(getResources().getString(R.string.url_phone))) {
			titleTextView.setText(" 전화번호 안내 ");
			headerIconView.setBackgroundResource(R.drawable.icon_header_phoneinfo);
		} else if (rootUrl.equals(getResources().getString(R.string.url_library))) {
			titleTextView.setText(" 도서관 ");
			headerIconView.setBackgroundResource(R.drawable.icon_header_library);
		}
	}
}
/* end of file */
